<?php
require_once($GLOBALS['ROO'] . 'common/File.php');
require_once($GLOBALS['ROO'] . 'Libraries/Pr_db/pr_historics.mex');

class Compliance {

    public function DuplicateBlock($SenderID, $ReceiverID, $SentAmount) {
        global $SESSCD, $sysTime;

        // SEC:: BLOCK DUP
        $GET = $GLOBALS['MYT']->db_array("SELECT FraID FROM
			facturas WHERE FraOrigen0 = $_SESSION[$SESSCD]
					AND DATE(FraFechaIngreso) = DATE('$sysTime')
					AND FraCliNumero = $SenderID
					AND FraBnfNumero = $ReceiverID
					AND FraEnviado = '$SentAmount'
					AND FraStatus NOT IN (1,9,10,21)");
        if (isset($GET[1])) {
            return $GET[1]['FraID'];
        } else {
            return false;
        }
    }

    private function AMLVerifyLevel($Level, $RemittanceHistory, $Position, $AmountToVerify) {
        $VerifiedCount = 0;
        $Verified['List'] = '';
        if (isset($Level[$Position])) {
            #Level position
            $Period = preg_split('/-/', $Level[$Position]['INTERV']);
            $CR = $RemittanceHistory[0];


            if ($Level[$Position]['INTERV'] != '0000-00-00') {
                $p = 1;
                while ($p <= $CR) {
                    $Inv_Time = preg_split('/-/', $RemittanceHistory[$p]['FraFecha']);
                    if (mktime(0, 0, 0, $Inv_Time[1], $Inv_Time[2], $Inv_Time[0]) < mktime(0, 0, 0, (date("m") - $Period[1]), (date("d") - $Period[2]), (date("Y") - $Period[0]))) {
                        $p = $CR;
                    } else {
                        $AmountToVerify += $RemittanceHistory[$p]['FraMontante'];
                        $VerifiedCount++;
                    }
                    $p++;
                }
            }
            for ($i = 1; $i <= $VerifiedCount; $i++) {
                $Verified['List'] .= $RemittanceHistory[$i]['FraID'] . ';';
            }
        }
        $Verified['Amount'] = $AmountToVerify;
        $Verified['List'] = substr($Verified['List'], 0, strlen($Verified['List']) - 1);
        return $Verified;
    }

    private function AMLVerifyLevelDocuments($ElementToVerify, $VerifyValue, $ProcessID, $LevelID, $CountryID) {
        $DocumentList = '';
        if ($ElementToVerify == 'SenderID') {
            $GETAML = $GLOBALS['MYT']->db_array("SELECT dnc_ID, dnc_Doc FROM hd_doctipos
            WHERE dnc_ID NOT IN
            (SELECT tdc_dnc FROM hd_documentos
            INNER JOIN hd_documentostipos ON dtd_Tipo = tdc_Id
            WHERE dtd_Cliente = $VerifyValue AND dtd_Status = 2
            AND tdc_dnc is not null
        UNION
            SELECT dnl_TipoDoc FROM hd_docdocumentos
            WHERE dnl_CL = $VerifyValue
            AND dnl_AML = $ProcessID
            AND dnl_Activo = 1)
            AND dnc_Tipo = 0
            AND dnc_Activo = 1 AND dnc_Nivel <= ($LevelID)
            AND dnc_Country = $CountryID");
        } else {
            $GETAML[0] = 1;
            $GETAML[1]['dnc_ID'] = 4;
        }
        if (isset($GETAML[1])) {
            for ($i = 1; $i <= $GETAML[0]; $i++) {
                //DO AML ALERT!
                $DocumentList .= $GETAML[$i]['dnc_ID'] . ',';
            }
            return substr($DocumentList, 0, strlen($DocumentList) - 1);
        } else {
            return false;
        }
    }

    public function AMLVerify($Channel, $ElementToVerify, $VerifyValue, $CountryID, $Amount, $Currency) {

        if ($Channel == 1) {
            $AmtField = '(FraEnviado+FraCargo-FraProm)';
        } elseif ($Channel == 2) {
            $AmtField = 'FraARecibir';
        }

        /* $VerifyValue
         *  SenderID
         *  SenderName
         *  ReceiverID
         *  ReceiverName
         */

        global $SESSID;
        $Return = array();
        $Return[0] = 0;
        $Return['Flag'] = 0;
        $Return['AMLLEVEL'] = 0; # Nao usado
        $Return['AMLCHECK'] = 0;
        $Return['AMLDESCR'] = '';
        $Return['AMLDOCREQ'] = '';
        $Return['AMLTYPEID'] = 0;

        $LastAmlProcess = 0;

        if ($ElementToVerify == 'SenderID') {
            #$Cond1 = ' amh_CLIENT = '.$VerifyID;
            $Cond1 = " amh_Verified = 1 AND amh_Value = $VerifyValue";
            $Cond2 = " FraCliNumero = $VerifyValue";
            $Cond3 = " amp_Client = $VerifyValue";
        } elseif ($ElementToVerify == 'SenderName') {
            $Cond1 = " amh_Verified = 2 AND amh_Value = '$VerifyValue'";
            $Cond2 = " FraCliNombre = '$VerifyValue'";
            $Cond3 = " amp_Client = 0";
        } elseif ($ElementToVerify == 'ReceiverID') {
            $Cond1 = " amh_Verified = 3 AND amh_Value = $VerifyValue";
            $Cond2 = " FraBnfNumero = $VerifyValue";
            $Cond3 = " amp_Client = 0";
        } elseif ($ElementToVerify == 'ReceiverName') {
            $Cond1 = " amh_Verified = 4 AND amh_Value = '$VerifyValue'";
            $Cond2 = " FraBnfNombre = '$VerifyValue'";
            $Cond3 = " amp_Client = 0";
        } else {
            die();
        }

// LAST PBC REPORT
        $getAlert = $GLOBALS['MYT']->db_array("SELECT
                amh_ID, amh_Operacion, amh_Status, amh_levelid
                FROM hd_amlalertas
                INNER JOIN facturas ON FraID = amh_Operacion
                LEFT JOIN facturasextjoins ON FraExtID = FraID
		WHERE $Cond1 AND amh_Status = '-1'
		ORDER BY amh_ID LIMIT 0,1");
        if (isset($getAlert[1])) {
            $LastAmlProcess = $getAlert[1]['amh_Operacion'];
            $Return[0] = 1;
            $Return['AMLCHECK'] = 2;
            $Return['AMLTYPEID'] = $getAlert[1]['amh_levelid'];
            $Return['Flag'] = 1;
            $Return['AML_MSGTYPE'] = 'clp_invalert2';
            $Return['AMLDESCR'] = '';
        }
        if ($Return['Flag'] == 0) {
            $Return['AMLCHECK'] = 1;
            // NO PBC ORDERS
            $RemittanceCurrency = array('', 'FraMonCobro', 'FraMonDPago');
            $Sent = $GLOBALS['MYT']->db_array("SELECT
                FraID, $AmtField AS FraMontante, DATE(FraFechaIngreso) AS FraFecha
                    FROM facturas
                    LEFT JOIN facturasextjoins ON FraID = FraExtID
                    WHERE $Cond2
                    AND FraID NOT IN (
                        SELECT frp_FraID
                            FROM facturas_pbc
                            INNER JOIN hd_amlprocess ON frp_PbcID = amp_ID
                            WHERE $Cond3 AND amp_Status = 6 AND amp_Channel = $Channel
                    )
                    AND FraStatus NOT IN (1,9,10,21)
                    AND $RemittanceCurrency[$Channel] = $Currency
                    AND FraModo = $Channel
                ORDER BY FraID DESC");
            // AML TYPE
            $AMLTYPE = $GLOBALS['MYT']->db_array("SELECT
		REF, INTERV, LEVEL, AMOUNT, DOCS, QUANT, REPORT
                    FROM hd_amllocks 
                    WHERE Country_ID = $CountryID
                    AND amll_Status = 2
                    AND amll_Currency = $Currency
                    AND amll_Channel = $Channel
                ORDER BY REPORT DESC, AMOUNT, INTERV DESC");
            for ($t = 1; $t <= $AMLTYPE[0]; $t++) {

                //MAKE SUM POOL
                $VerifiedLevel = $this->AMLVerifyLevel($AMLTYPE, $Sent, $t, $Amount);

                //MAKE SUM NEXT POOL
                $VerifiedNextLevel = $this->AMLVerifyLevel($AMLTYPE, $Sent, ($t + 1), $Amount);
                // CHECK POOL > LEVEL
                # Desactiva limite ordinario do compliancce #  && ($jt <= $AMLTYPE[$t]['QUANT'] || $jtn <= $AMLTYPE[$t+1]['QUANT'])
                if (isset($AMLTYPE[$t + 1]) && $VerifiedLevel['Amount'] >= $AMLTYPE[$t]['AMOUNT'] && $VerifiedNextLevel['Amount'] < $AMLTYPE[$t + 1]['AMOUNT']) {
                    $VerfiedLevelDocumentation = $this->AMLVerifyLevelDocuments($ElementToVerify, $VerifyValue, $LastAmlProcess, $AMLTYPE[$t]['REF'], $CountryID);
                    if ($VerfiedLevelDocumentation) {
                        $Return[0] = 1;
                        $Return['AMLDOCREQ'] = $VerfiedLevelDocumentation;
                        $Return['AML_MSGTYPE'] = 'clp_invalert' . $AMLTYPE[$t]['REPORT'];
                        $Return['AMLDESCR'] = $VerifiedLevel['List'];
                        $Return['AMLTYPEID'] = $AMLTYPE[$t]['REF'];
                        $Return['AMLTYPED'] = $AMLTYPE[$t]['DOCS'];
                        $Return['Flag'] = $AMLTYPE[$t]['REPORT'];
                        $t = $AMLTYPE[0] + 1;
                    }
                }
            }
        }
        return $Return;
    }

    public function AMLPrepareBlock($Channel, $EditRemittance, $doCompliance, $Flag) {
        // BLOCK CLIENT
        /* $AMLBLK = $GLOBALS['MYT']->db_query("INSERT INTO hd_bloqueos
          (blk_Fecha, blk_Codigo, lbk_Tipo, lbk_Nivel, blk_Usuario, blk_Informacion, blk_STATUS)
          VALUES
          ('{$Fi7}',{$Fi26},1,{$AMLLEVEL},{$Fi24},'PBC - COMPLIANCE',1)");
          $GETBLK = $GLOBALS['MYT']->db_array("SELECT blk_ID FROM hd_bloqueos
          WHERE blk_Codigo = {$Fi26} ORDER BY blk_ID DESC LIMIT 0,1");
          $GETBLK = $GETBLK[1]['blk_ID']; */

        /* $CLBLK = $GLOBALS['MYT']->db_query("UPDATE clientes
          SET CliBloqueado = 1
          WHERE CliNumero = {$Fi26}"); */

        if ($doCompliance > 0 && $Flag > 0) {
            $RemittanceStatus = 14;
        } else {
            if ($Channel == 1) {
                $RemittanceStatus = 2;
            } elseif ($Channel == 2) {
                $RemittanceStatus = 16;
            }
        }
        if ($EditRemittance > 0 && $doCompliance > 0 && $Flag > 0) {
            $GLOBALS['MYT']->db_query("UPDATE facturas SET FraStatus = $RemittanceStatus WHERE FraID = $EditRemittance");
        }
        return $RemittanceStatus;
    }

    public function AMLBlock($doCompliance, $Flag, $Remessa, $ElementToVerify, $VerifiedValue, $Description, $Level, $Channel) {
        global $sysTime;
        $amlElements = array('SenderID' => 1, 'SenderName' => 2, 'ReceiverID' => 3, 'ReceiverName' => 4);
        $Status = 0;
        $Return[0] = 0;
        if ($doCompliance > 0) {
            if ($Flag > 0) {
                $Status = '-1';
            }
            if ($doCompliance == 1) {
                $Alert = tuga_multiquery("CALL cpl_block(@amlID,$Remessa,'$sysTime','$Status',$amlElements[$ElementToVerify],'$VerifiedValue',$Level,$Channel,'$Description',@amlAlert,@amlReport); SELECT @amlAlert,@amlReport;");
                $Return['MSGTYPE'] = 'cld_invalert' . $Alert[0][1]['amlReport'];
                $Return[0] = 1;
            } elseif ($doCompliance == 2) {
                $Alert = tuga_multiquery("CALL cpl_block(1,$Remessa,'$sysTime','$Status',$amlElements[$ElementToVerify],'$VerifiedValue',$Level,$Channel,'$Description',@amlAlert,@amlReport); SELECT @amlAlert,@amlReport;");
            }
            $Return['ID'] = $Alert[0][0]['amlAlert'];
        }
        return $Return;
    }

    public function AMLUnblock($AmlID, $AmlComment, $AmlReply, $AmlStatus, $AmlRemittance, $AmlUnblock) {
        global $sysTime, $SESSID;
        $RemittanceNewStatus = 2;
        if ($AmlID > 0) {
            $GLOBALS['MYT']->db_query("UPDATE hd_amlalertas
					SET amh_Comentario = '$AmlComment',
					amh_Reply = '$AmlReply',
					amh_Status = '$AmlStatus'
					WHERE amh_ID = $AmlID");
            $AMLDOps = $GLOBALS['MYT']->db_array("SELECT amd_Desc, amh_Channel FROM hd_amldetalle
                                        INNER JOIN hd_amlalertas ON amd_Alerta = amh_ID
					WHERE amd_Alerta = $AmlID");
            $POOL = $AmlRemittance;
            if ($AMLDOps[1]['amd_Desc'] != '') {
                $POOL .= ',' . str_replace(';', ',', $AMLDOps[1]['amd_Desc']);
            }
            if ($AMLDOps[1]['amh_Channel'] == 1) {
                $RemittanceNewStatus = 2;
            } else {
                $RemittanceNewStatus = 16;
            }
            if ($AmlUnblock > 0 && $AmlStatus == 1) {
                if ($GLOBALS['MYT']->db_query("UPDATE facturas
					SET FraStatus = $RemittanceNewStatus
					WHERE FraID IN ($POOL)
						AND FraStatus IN (12,13,14)") == true) {
                    system_hs($sysTime, 'AML_CLOSE', $AmlID);
                }
            }
        }
    }

    public function ISRBlock($SenderID, $RemittanceID) {
        global $SESSID;
        $GLOBALS['MYT']->db_query("UPDATE hd_isralert SET isr_Operacion = $RemittanceID, isr_Status = 3
            WHERE isr_Operacion IS NULL AND isr_User = $_SESSION[$SESSID] AND isr_Client = $SenderID");
    }

    public function ISRUnblock($Alert, $Status, $RemittanceID, $unblockCheck, $Description) {
        if (isset($Alert)) {
            $Details = $GLOBALS['MYT']->db_query("UPDATE hd_isralert
					SET isr_Description = '$Description',
					isr_Status = $Status
					WHERE isr_ID = $Alert");
            if ($unblockCheck > 0 && $Status == 1) {
                $Op = $GLOBALS['MYT']->db_query("UPDATE facturas
					SET FraStatus = 2
					WHERE FraID = $RemittanceID
						AND FraStatus = 8");
            }
            return true;
        } else {
            return false;
        }
    }

    public function AMLBulkBlock($Channel, $ElementToVerify, $CountryID, $SelectedOrders, $Currency) {
        $amlField1 = array('', 'FraEnviado', 'FraARecibir');
        $amlElements = array('SenderID' => 1, 'SenderName' => 2, 'ReceiverID' => 3, 'ReceiverName' => 4);
        $amlField2 = array('', 'FraCliNumero', 'FraCliNombre', 'FraBnfNumero', 'FraBnfNombre');

        $GET = $GLOBALS['MYT']->db_array("SELECT FraID,FraCliNombre,FraCliNumero,FraBnfNombre,FraBnfNumero,FraEnviado,FraARecibir
                            FROM facturas
                            LEFT JOIN facturasextjoins ON FraID = FraExtID
                            WHERE FraID IN ($SelectedOrders) AND FraStatus = 16 AND FraModo = $Channel
                            AND FraMonDPago = $Currency");
        for ($i = 1; $i <= $GET[0]; $i++) {
            $Result = $this->AMLVerify($Channel, $ElementToVerify, $GET[$i][$amlField2[$amlElements[$ElementToVerify]]], $CountryID, $GET[$i][$amlField1[$Channel]], $Currency);
            if ($Result['AMLCHECK'] > 0) {
                if ($this->AMLPrepareBlock($Channel, $GET[$i]['FraID'], $Result['AMLCHECK'], $Result['Flag'])) {
                    $this->AMLBlock($Result['AMLCHECK'], $Result['Flag'], $GET[$i]['FraID'], $ElementToVerify, $GET[$i][$amlField2[$amlElements[$ElementToVerify]]], $GET[$i]['FraID'], $Result['AMLTYPEID'], $Channel);
                }
            }
        }
    }

    public function PbcProcessAdd() {
        
    }

    public function PbcProcessEdit() {
        
    }

    public function PbcProcessClose() {
        
    }

    public function AmlDocumentAdd($AlertID,$DocTipo,$DncTipo,$FileData,$DocObserv,$AddDocumentsToClient) {
        global $sysTime, $SESSID, $SESSOF;
        if ($FileData != '') {
            $prefix = 1;

            $AML_CL = $GLOBALS['MYT']->db_array("SELECT amh_CLIENT FROM hd_amlalertas WHERE amh_ID = $AlertID");
            $AML_CL = $AML_CL[1]['amh_CLIENT'];
            $AMLDOCID = $GLOBALS['MYT']->db_array("SELECT dnl_ID
  			FROM hd_docdocumentos ORDER BY dnl_ID DESC LIMIT 0,1");
            if (isset($AMLDOCID[1])) {
                $prefix = $AMLDOCID[1]['dnl_ID'];
            }
            $file = $_FILES['FILE'];
            $app = date("ymdHis") . $prefix;
            $ext = explode('.', $FileData['name']);
            $exts = count(explode('.', $file['name'])) - 1;
            $ext = $ext[$exts];
            $prefix = md5($app) . '.' . $ext;
            $dir = $GLOBALS['DOC'] . 'PRFLDOCS/' . $AML_CL . '/';
            if (!file_exists($dir)) {
                mkdir($dir);
            }
            $NewFile = new File();
            if ($NewFile->FileImport($file, $ext, $prefix, $dir) == true) {
                $GLOBALS['MYT']->db_query("INSERT INTO hd_docdocumentos (dnl_TipoDoc, dnl_CL, dnl_FechaEntrega, dnl_Usuario,dnl_AML,dnl_OFFICE,dnl_FILE,dnl_dncTipo,dnl_Observ)
		VALUES ($DocTipo,$AML_CL,'$sysTime',$_SESSION[$SESSID],$AlertID,$_SESSION[$SESSOF],'$prefix',$DncTipo,'$DocObserv')");
                if ($AddDocumentsToClient>0) {
                    $GLOBALS['MYT']->db_query("INSERT
			INTO hd_documentos
			(dtd_Cliente,
				dtd_Tipo,
				dtd_Numero,
				FILE,
				dtd_CopiaDoc,
				dtd_Fecha,
				dtd_Usuario,
				DC_OFFICE)
			VALUES ($AML_CL,$DocTipo,'','$prefix',1,'$sysTime',$_SESSION[$SESSID],$_SESSION[$SESSOF])");
                }
                return true;
            }
        }
    }

    public function AmlDocumentEdit($DocID, $DocType) {
        $GLOBALS['MYT']->db_query("UPDATE hd_docdocumentos SET dnl_TipoDoc =$DocType WHERE dnl_ID = $DocID");
        return true;
    }

    public function AmlDocumentDelete($DocID) {
        $GLOBALS['MYT']->db_query("UPDATE hd_docdocumentos SET dnl_TipoDoc = 0 WHERE dnl_ID = $DocID");
        return true;
    }

}

?>
